<template>
  <div>
    <el-alert
      v-if="adminLevel < requiredLevel"
      title="(⊙o⊙)…您的权限不能访问此页面"
      type="warning"
      :closable="false"
    ></el-alert>
    <div v-else>
      <div class="card">
        <div class="card-header">
          <strong>选择人员</strong>
          <span v-if="nameList"
            >&emsp;({{ selectedNames.length }}/{{ nameList.length }})</span
          >
          <button type="button" class="close" @click="showNameSelector = true">
            &#43;
          </button>
        </div>
        <div class="card-body my-card-body text-center">
          <p class="text-muted small" v-show="selectedNames.length == 0">
            单击右上角的加号添加
          </p>
          <div v-show="selectedNames.length > 0">
            <span
              class="badge my-badge text-center"
              v-for="(name, id) in selectedNames"
              :key="id"
            >
              {{ name }}
              <button
                type="button"
                class="close my-close"
                @click="selectName(name)"
              >
                &times;
              </button>
            </span>
          </div>
        </div>
      </div>
      <p>&emsp;</p>
      <div class="card">
        <div class="card-header">
          <strong>设定值</strong>
          <span>&ensp;({{ editedItems.length }})</span>
          <button type="button" class="close" @click="editorOpen()">
            &#43;
          </button>
        </div>
        <div class="card-body my-card-body text-center">
          <p class="text-muted small" v-show="editedItems.length == 0">
            单击右上角的加号添加
          </p>
          <table
            class="table table-hover table-sm my-table"
            v-show="editedItems.length > 0"
          >
            <tbody>
              <tr v-for="(item, id) in editedItems" :key="id">
                <td class="my-cell text-middle align-middle">
                  {{ item.title }}
                </td>
                <td class="my-cell text-middle align-middle">
                  {{ item.value }}
                </td>
                <td class="my-cell text-right align-middle">
                  <div class="btn-group">
                    <button
                      type="button"
                      class="btn btn-link"
                      @click="editorOpen(item.title, item.value)"
                    >
                      修改
                    </button>
                    <button
                      type="button"
                      class="btn btn-link"
                      @click="editedItems.splice(id, 1)"
                    >
                      删除
                    </button>
                  </div>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
      <p>&emsp;</p>
      <div
        class="alert alert-success alert-dismissible"
        v-show="okMsg.length > 0"
      >
        <button type="button" class="close" @click="okMsg = ''">&times;</button>
        <strong>完成:</strong>
        {{ okMsg }}
      </div>
      <div
        class="alert alert-danger alert-dismissible"
        v-show="errMsg.length > 0"
      >
        <button type="button" class="close" @click="errMsg = ''">
          &times;
        </button>
        <strong>错误:</strong>
        {{ errMsg }}
      </div>
      <p>&emsp;</p>
      <p class="text-center">
        <button type="button" class="btn btn-dark btn-lg" @click="doUpdate">
          执行
        </button>
      </p>
      <maskView v-if="showConfirm">
        <div>
          <h4>将修改以下人员的信息</h4>
          <p>
            <span v-for="(name, id) in selectedNames" :key="id">
              {{ name }}
              <span v-if="id < selectedNames.length - 1">、</span>
            </span>
            <span>（共{{ selectedNames.length }}人）</span>
          </p>
          <ul>
            <li v-for="(item, id) in editedItems" :key="id">
              {{ item.title }}&emsp;修改为&emsp;{{ item.value }}
            </li>
          </ul>
          <div class="btn-group">
            <button type="button" class="btn btn-dark btn-lg" @click="doPost">
              确定
            </button>
            <button
              type="button"
              class="btn btn-dark btn-lg"
              @click="showConfirm = false"
            >
              取消
            </button>
          </div>
        </div>
      </maskView>
      <nameSelector
        v-if="showNameSelector"
        :selected="selectedNames"
        @close="showNameSelector = false"
        @select="selectName"
      ></nameSelector>
      <!-- new -->
      <editorView
        v-if="editor.show"
        @close="editorClose"
        @commit="editorCommit"
        :currentValue="editor.value"
        :currentTitle="editor.title"
      ></editorView>
    </div>
  </div>
</template>

<script>
import editorView from "@/views/editorView/";
import nameSelector from "./nameSelector.vue";
import maskView from "@/views/maskView";
export default {
  name: "batchView",
  data() {
    return {
      requiredLevel: 2,
      editor: {
        show: false,
        value: "",
        title: "",
      },
      selectedNames: [],
      showNameSelector: false,
      editedItems: [],
      showItemEditor: false,
      editItemIndex: -1,
      postData: null,
      showConfirm: false,
      errMsg: "",
      okMsg: "",
    };
  },
  components: {
    nameSelector,
    maskView,
    editorView,
  },
  computed: {
    adminLevel() {
      return this.$store.getters.adminLevel;
    },
    staffList() {
      return this.$store.state.staffList;
    },
    nameList() {
      return this.$store.state.nameList;
    },
    dataList() {
      let dataConfig = this.$store.state.dataConfig;
      if (!dataConfig) return null;
      let dataList = new Array();
      for (let i = 0; i < dataConfig.length; i++) {
        if (!dataConfig[i].is_basic) dataList.push(dataConfig[i]);
      }
      return dataList;
    },
    itemList() {
      let dataConfig = this.$store.state.dataConfig;
      if (!dataConfig) return null;
      let itemList = new Array();
      for (let i = 0; i < dataConfig.length; i++) {
        if (!dataConfig[i].is_basic) itemList.push(dataConfig[i].title);
      }
      return itemList;
    },
  },
  methods: {
    // new function
    editorOpen(title, value) {
      this.editor.value = value;
      this.editor.title = title;
      this.editor.show = true;
    },
    editorClose() {
      this.editor.value = "";
      this.editor.title = "";
      this.editor.show = false;
    },
    editorCommit(payload) {
      this.editorClose();
      if (this.isDev) window.console.log(payload);
      for (let i = 0; i < this.editedItems.length; i++) {
        if (this.editedItems[i].title == payload.title) {
          this.editedItems[i].value == payload.value;
          return null;
        }
      }
      this.editedItems.push({
        title: payload.title,
        value: payload.value,
      });
    },
    selectName(nameStr) {
      let idx = this.selectedNames.indexOf(nameStr);
      if (idx > -1) {
        this.selectedNames.splice(idx, 1);
      } else {
        this.selectedNames.push(nameStr);
      }
      window.console.log(this.selectedNames);
    },
    doUpdate() {
      this.postData = null;
      this.errMsg = "";
      this.okMsg = "";
      if (this.selectedNames.length > 0 && this.editedItems.length > 0) {
        let users = new Array();
        for (let i = 0; i < this.selectedNames.length; i++) {
          users.push({
            id: this.getUserID(this.selectedNames[i]),
            name: this.selectedNames[i],
          });
        }
        this.postData = {
          users: users,
          items: this.editedItems,
        };
        this.showConfirm = true;
      } else {
        this.errMsg = "未选择人员或设定值";
      }
    },
    resetData() {
      this.showConfirm = false;
      this.postData = null;
      this.selectedNames = [];
      this.editedItems = [];
      this.okMsg = "";
      this.errMsg = "";
    },
    doPost() {
      this.$store.commit("setLoading", true);
      this.axios
        .post("api/", {
          action: "batch_modify",
          payload: {
            login_data: this.$store.state.loginData,
            content: this.postData,
          },
        })
        .then((response) => {
          if (this.isDev) window.console.log(response.data);
          if (response.data.result == "success") {
            let msg =
              "成功更新" +
              this.selectedNames.length * this.editedItems.length +
              "条数据";
            this.resetData();
            this.$nextTick(() => {
              this.okMsg = msg;
            });
            if (this.isDev) window.console.log(msg);
          } else {
            this.errMsg = "提交数据失败了";
          }
          this.$store.commit("setLoading", false);
        });
    },
    getUserID(userName) {
      for (let i = 0; i < this.staffList.length; i++) {
        if (this.staffList[i].clientName == userName) {
          return this.staffList[i].number;
        }
      }
      return null;
    },
  },
  watch: {
    selectedNames() {
      this.errMsg = "";
      this.okMsg = "";
      this.postData = null;
    },
    editedItems() {
      this.errMsg = "";
      this.okMsg = "";
      this.postData = null;
    },
  },
  mounted() {
    if (!this.$store.state.staffList) this.$store.dispatch("getStaffList");
  },
};
</script>

<style scoped>
.my-badge {
  font-size: 0.95em;
  font-weight: normal;
  border-radius: 0.75em;
  margin: 0.3em 0.15em;
  padding: 0.4em 0.4em 0.4em 0.5em;
  background: #eee;
}
.my-close {
  font-size: 1.25em;
  line-height: 0.8em;
  margin-left: 0.25em;
}
.my-cell {
  /* width:33.3%; */
}
.my-table {
  margin: 0;
}
.my-card-body {
  padding: 0;
  min-height: 2em;
}
.my-btn {
  font-size: 0.8em;
  margin: 0;
  line-height: 1em;
}
</style>